package com.lagou.edu.service.impl;

import com.lagou.edu.bean.LagouAuthCode;
import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.edu.service.LagouAuthCodeService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import service.CodeService;
import service.EmailService;

import java.util.Date;
import java.util.Optional;

/**
 * @ClassName LagouAuthCodeServiceImpl
 * @Description TODO
 * @Auth ying.xiao
 * @Date 2021/4/20
 * @Version 1.0.0
 */
@Service
public class LagouAuthCodeServiceImpl implements CodeService {

    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;

    @Reference
    private EmailService emailService;

    public boolean create(String email) {

        //创建六位随机数字作为验证码
        int code = (int)((Math.random() * 9 + 1) * 100000);

        //保存用户获取验证码的有效时长
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code+"");
        lagouAuthCode.setCreateTime(new Date());
        lagouAuthCode.setExpireTime(new Date(lagouAuthCode.getCreateTime().getTime() + 600000));
        lagouAuthCodeDao.save(lagouAuthCode);

        //发送通知邮件
        boolean b = emailService.sendEmail(email, code+"");
        return b;
    }
    @Override
    public Integer validate(String email, String code) {
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code);
        Optional<LagouAuthCode> one = lagouAuthCodeDao.findOne(Example.of(lagouAuthCode));
        if(!one.isPresent()){
            return 1;
        }
        LagouAuthCode lagouAuthCode1 = one.get();
        //验证码不正确
        if(null == lagouAuthCode1 || null == lagouAuthCode1.getId()){
            return 1;
        }
        //验证码超过10分钟
        if(lagouAuthCode1.getExpireTime().getTime()< new Date().getTime()){
            return 2;
        }
        return 0;
    }
}
